package ca.tatham.senssim;

import java.util.Iterator;
import java.util.LinkedList;

public class RingBuffer<T> implements Iterable<T>
{
  private final LinkedList<T> m_queue = new LinkedList<T>();
  private final int m_maxSize;

  public RingBuffer(int maxSize)
  {
    m_maxSize = maxSize;
  }

  public Iterator<T> iterator()
  {
    return m_queue.iterator();
  }

  /**
   * 
   * @param obj
   * @return true if the object was not already in the buffer
   */
  public boolean add(T obj)
  {
    int index = -1;
    if ((index = m_queue.indexOf(obj)) != -1)
    {
      // move the object to the end of the list
      m_queue.add(m_queue.remove(index));
      return false;
    }
    m_queue.add(obj);
    if (m_queue.size() == m_maxSize)
    {
      m_queue.removeFirst();
    }
    return true;
  }

}
